package ar.uba.dc.cmovil.tripplanner.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import ar.uba.dc.cmovil.tripplanner.R;
import ar.uba.dc.cmovil.tripplanner.domain.Location;
import ar.uba.dc.cmovil.tripplanner.domain.Place;
import ar.uba.dc.cmovil.tripplanner.domain.Trip;
import ar.uba.dc.cmovil.tripplanner.domain.TripsManager;
import ar.uba.dc.cmovil.tripplanner.services.FindTweetsCountByPlaceTask;
import ar.uba.dc.cmovil.tripplanner.services.GetCoordinatesByNameTask;
import ar.uba.dc.cmovil.tripplanner.services.HttpTaskHandler;
import ar.uba.dc.cmovil.tripplanner.services.TwitterService;
import ar.uba.dc.cmovil.tripplanner.utils.DateFormatter;
import ar.uba.dc.cmovil.tripplanner.utils.PlaceUtils;
import ar.uba.dc.cmovil.tripplanner.utils.TextUtils;
import ar.uba.dc.cmovil.tripplanner.view.PlacesView;
import ar.uba.dc.cmovil.tripplanner.widget.PlaceItemWidget;
import ar.uba.dc.cmovil.tripplanner.widget.TextAndDateWidget;
import twitter4j.TwitterException;


public class PlacesActivity extends Activity implements PlaceItemWidget.PlaceItemEventsHandler {

    public static final String SELECTED_TRIP_ID = "selected_trip_id";
    private Trip trip;
    private PlacesView view;
    private TripsManager tripsManager;
    private TwitterService twitter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_places);

        Intent intent = getIntent();

        this.tripsManager = TripsManager.getInstance();
        trip = tripsManager.getTripById((String) intent.getSerializableExtra(SELECTED_TRIP_ID));

        twitter = TwitterService.getInstance();

        view = new PlacesView(this);
        view.setTripName(trip.getName());
        view.setTripStartDate(DateFormatter.formatDate(trip.getStartDate()));
        view.addPlaceButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                addPlaceButtonClicked();
            }
        });

        List<String> places = new ArrayList<String>();
        for (final Place place : trip.getPlaces()) {
            view.addPlace(place);
            places.add(place.getName());
        }

        new FindTweetsCountByPlaceTask(new HttpTaskHandler<Map<String, Integer>>() {
            @Override
            public void onSuccess(Map<String, Integer> result) {
                for (Place place : trip.getPlaces()) {
                    int otherUsers = result.containsKey(place.getName()) ? result.get(place.getName()) : 0;
                    view.setOtherUsersAtPlace(place, otherUsers == 0 ? 0 : otherUsers - 1);
                }
            }

            @Override
            public void onFail() {
            }
        }).execute(places);

        setTitle(trip.getName());
    }

    public void selectPlace(Place place) {
        Intent showPlaceIntent = new Intent(this, PlaceActivity.class);
        showPlaceIntent.putExtra(PlaceActivity.SELECTED_PLACE, place);
        startActivity(showPlaceIntent);
    }

    public void addPlaceButtonClicked() {
        final TextAndDateWidget widget = new TextAndDateWidget(this, "Nombre del lugar", trip.getStartDate());

        new AlertDialog.Builder(this)
                .setTitle("Nuevo lugar")
                .setView(widget)
                .setPositiveButton("Guardar", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        if (!TextUtils.isEmpty(widget.getText())) {
                            assert widget.getDate().compareTo(trip.getStartDate()) <= 0;

                            final String name = widget.getText();
                            GetCoordinatesByNameTask task = new GetCoordinatesByNameTask(PlacesActivity.this,
                                    new HttpTaskHandler<Location>() {
                                        @Override
                                        public void onSuccess(Location result) {
                                            Place place = new Place(name, widget.getDate());
                                            place.setLocation(result);
                                            addPlaceToTrip(place);
                                        }

                                        @Override
                                        public void onFail() {
                                            System.out.println("Error al obtener las coordenadas " +
                                                    "del lugar ingresado");
                                        }
                                    });
                            task.execute(name);
                        }
                    }
                })
                .setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        // Canceled.
                    }
                })
                .show();
    }

    public void addPlaceToTrip(Place place) {
        view.addPlace(place, twitter.countTweetsByPlace(place.getName()));
        trip.add(place);
        this.tripsManager.saveTrips();

        try {
            twitter.postPlace(place.getName());
        } catch (TwitterException e) {
            e.printStackTrace();
        }
    }

    private void deletePlace(Place place) {
        view.removePlace(place);
        trip.remove(place);
        tripsManager.saveTrips();

        twitter.removeTweetByPlace(place.getName());
    }

    @Override
    public void onPlaceDelete(final Place place) {
        new AlertDialog.Builder(this)
                .setIcon(android.R.drawable.ic_dialog_alert)
                .setTitle(R.string.delete)
                .setMessage(R.string.confirm_delete_place)
                .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        deletePlace(place);
                    }

                })
                .setNegativeButton(R.string.no, null)
                .show();
    }

    @Override
    public void onPlaceSelected(Place place) {
        selectPlace(place);
    }

    @Override
    public void onAddToCalendarClicked(Place place) {
        PlaceUtils.addToCalendar(this, place);
    }
}
